package com.paireach.szwolaiyun.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.paireach.szwolaiyun.R;
import com.paireach.szwolaiyun.sz_common_widget.activity.BaseActivity;
import com.paireach.szwolaiyun.sz_util.LogUtil;
import com.paireach.szwolaiyun.sz_util.Md5;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import szwolaiyun.paireach.com.szwolaizhuang.model.business.User;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.AppEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.HttpErrorEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.HttpSuccessEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.requestTag.RequestTag;
import szwolaiyun.paireach.com.szwolaizhuang.net.UserRequest;
import szwolaiyun.paireach.com.szwolaizhuang.net.json.JsonPaser;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "LoginActivity";
    private Button login;
    private EditText userName;
    private EditText userPassword;
    private String gpsStatus = "否";//gps未开启
    private String simSerialNumber;
    private String simPhoneNumber;
    private PackageInfo packageInfo;
    private int versionCode;
    private String model;
    private String androidVersion;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initControl();
    }

    private void initControl() {
        login = (Button) findViewById(R.id.btn_login);
        userName = (EditText) findViewById(R.id.et_login_phone);
        userPassword = (EditText) findViewById(R.id.et_login_password);
        login.setOnClickListener(this);
        findViewById(R.id.layout_top_back).setVisibility(View.GONE);
        ((TextView) findViewById(R.id.layout_top_change)).setText("登录");

        getPhoneInfo();//登陆时时候把这个参数也返回
    }

    private void getPhoneInfo() {
        TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        simSerialNumber = manager.getSimSerialNumber();
        //本机的手机号
        simPhoneNumber = manager.getLine1Number();
        //版本号
        try {
            packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            versionCode = packageInfo.versionCode;
        }

        //手机型号
        model = Build.MODEL;
        //android系统版本号
        androidVersion = Build.VERSION.RELEASE;

        LogUtil.d(TAG,"simSerialNumber = "+ simSerialNumber +"simPhoneNumber="+ simPhoneNumber+"versionCode="+versionCode+"model="
                + model +"androidVersion="+ androidVersion);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                if (showIsEmpty()) {
                    String username = userName.getText().toString();
                    String pass = userPassword.getText().toString();

                    Map<String, Object> map = new HashMap<>();
                    map.put("driverTel", username);
                    try {
                        map.put("driverPwd", Md5.getStringMD5(pass));
                    } catch (Exception e) {
                        map.put("driverPwd", "");
                    }
                    map.put("gpsStatus", gpsStatus);
                    map.put("simSerialNumber", simSerialNumber);
                    map.put("simPhoneNumber", simPhoneNumber);
                    map.put("model",model);
                    map.put("androidVersion",androidVersion);
                    map.put("versionCode",versionCode);

                    JSONObject object = new JSONObject(map);
                    String loginData = object.toString();
                    LogUtil.d(TAG,"loginData="+loginData);

                    showProgressDialog();
                    new UserRequest().passwordLogin_app3(loginData);
//                    new UserRequest().passwordLogin_app(username, pass);
                    //登陆时把GPS的状态也返回
//                    new UserRequest().passwordLogin_app2(username, pass,getGpsStatus(LoginActivity.this),simSerialNumber,simPhoneNumber);
                }
                break;
        }
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        if (event.getRequestTag() == RequestTag.USER_LOGIN) {
            dismissProgressDialog();
            showToast(event.getErrorMessage());
        }
    }

    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        if (event.getRequestTag() == RequestTag.USER_LOGIN) {
            dismissProgressDialog();
            JsonPaser.parseUserInfo(event.getJson());
        }
    }

    @Override
    public void applicationEvent(AppEvent event) {
        super.applicationEvent(event);
        if (event.getTag().equals("user_login_paser")) {
            if (event.getCode() == 0) {
                User user = (User) event.getObj1();
                User.saveUserInfo(this, user);
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();

            } else {
                showToast(event.getExtraInfo());
            }
        }
    }

    private boolean showIsEmpty() {
        if (TextUtils.isEmpty(userName.getText().toString()) || TextUtils.isEmpty(userPassword.getText().toString())) {
            Toast.makeText(this, "用户名或密码不可为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public String getGpsStatus(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean isOpenGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
//        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isOpenGps){
            gpsStatus = "是";
        } else {
            gpsStatus = "否";
        }
        return  gpsStatus;
    }
}

